package com.sunflower.common.mybatis.core.page;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sunflower.common.core.interceptor.SFunction;
import com.sunflower.common.core.utils.reflect.ReflectUtils;
import io.github.linpeilie.annotations.AutoMapping;
import lombok.Data;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * TODO
 *
 * @author: SunLuQuan
 * @Date: 2024年04月09日 17:45
 * @Description: DefaultSorting
 */
@Data
public class DefaultSorting<T> implements ISorting {

    @AutoMapping(ignore = true)
    private List<OrderItem> orders;

    @Override
    public List<OrderItem> orders() {
        return orders;
    }

    public LambdaQueryWrapper<T> buildLambdaQueryWrapper() {
        return buildQueryWrapper().lambda();
    }

    public QueryWrapper<T> buildQueryWrapper() {
        QueryWrapper<T> queryWrapper = Wrappers.query();
        if (CollectionUtil.isNotEmpty(orders)) {
            for (OrderItem order : orders) {
                queryWrapper.orderBy(true, order.isAsc(), order.getColumn());
            }
        }
        return queryWrapper;
    }

    private List<OrderItem> _getOrders() {
        if (ObjectUtil.isNull(orders)) {
            orders = new ArrayList<>();
        }
        return orders;
    }

    /**
     * 添加新的排序条件，构造条件可以使用工厂
     *
     * @param items 条件
     * @return
     */
    public void addOrder(OrderItem... items) {
        orders.addAll(Arrays.asList(items));
    }

    /**
     * 添加新的排序条件，构造条件可以使用工厂
     *
     * @param items 条件
     * @return
     */
    public void addOrder(List<OrderItem> items) {
        orders.addAll(items);
    }

    public void addOrder(SFunction<T, ?> columnFun, boolean isAsc) {
        String column = ReflectUtils.getFieldName(columnFun);
        if (isAsc) {
            orders.add(OrderItem.asc(column));
        } else {
            orders.add(OrderItem.desc(column));
        }
    }

    public void addOrder(SFunction<T, ?> columnFun) {
        addOrder(columnFun, true);
    }
}
